package com.bhs.sansong.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.Constants;
import com.bhs.sansong.bean.LoginBean;
import com.bhs.sansong.bean.OrderDetailsBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.login.SelectIndustryActivity;
import com.bhs.sansong.ui.main.MainActivity;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class MyUtils {

    public static String getPayType(int type) {
        switch (type) {
            case 1:
                return "微信";
            case 2:
                return "支付宝";
            default:
                return "银行卡";
        }
    }


    /**
     * @param urlStr    url字符串。
     * @param paramName 指定参数名称。
     * @return NA.
     * @desc 获取url中指定参数的值。
     */
    public static String readValueFromUrlStrByParamName(String urlStr, String paramName) {
        if (urlStr != null && urlStr.length() > 0) {
            int index = urlStr.indexOf("?");
            String temp = (index >= 0 ? urlStr.substring(index + 1) : urlStr);
            String[] keyValue = temp.split("&");
            String destPrefix = paramName + "=";
            for (String str : keyValue) {
                if (str.indexOf(destPrefix) == 0) {
                    return str.substring(destPrefix.length());
                }
            }
        }
        return null;
    }

    public static String getOrderType2(int type, int orderType) {

        String placeOrder = type == 1 ? "指派" : "极速";
        String efficiency = orderType == 1 ? "普运" : "快运";
        return placeOrder + efficiency;
    }

    public static String format2(double value) {

        long l = (long) (value * 10);
        double d = l / 10D;

        return String.valueOf(d);
    }

    public static String getScoreGrade(float parseDouble) {
        if (parseDouble <= 1) {
            return "极差";
        } else if (parseDouble > 1 && parseDouble <= 2) {
            return "差";
        } else if (parseDouble > 2 && parseDouble <= 3) {
            return "一般";
        } else if (parseDouble > 3 && parseDouble <= 4) {
            return "好";
        } else {
            return "很好";
        }
    }

    public static String isInvoice(int type) {
        return "";
        // return type == 1 ? "开发票" : "不开发票";
    }

    public static void setText(TextView textView, String text) {
        textView.setText(TextUtils.isEmpty(text) ? "" : text);
    }


    /**
     * 交货方式
     */
    public static String getDeliveryType(int type) {
        return type == 1 ? "自送专线" : "上门提货";
    }

    /**
     * 订单类型
     */
    public static String getOrderType(int type) {
        return type == 1 ? "指派下单" : "极速下单";
    }

    /**
     * 配送方式
     */
    public static String getDistributionType(int type) {
        return type == 1 ? "送货上门" : "自提";
    }


    /**
     * 配送方式
     *
     * @param type
     * @return
     */
    public static String getHaulageTime(int type, int max, int min) {
        switch (type) {
            case 1:
                return String.format("普运/%s-%s天", min, max);
            case 2:
                return String.format("快运/%s-%s天", min, max);
            default:
                return "商议";
        }
    }

    /**
     * 屏幕高度
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        wm.getDefaultDisplay().getRealSize(point);
        return point.y;
    }

    /**
     * 屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        wm.getDefaultDisplay().getRealSize(point);
        return point.x;
    }

//    /**
//     * 水印
//     */
//    public static String watermark(String path) {
//        if (path.contains("http")) {
//            return String.format("%s?x-oss-process=style/sansong_app", path);
//        } else {
//            return path;
//        }
//    }

    /**
     * 水印
     */
    public static String watermark(String path) {
        return path;
    }

    //登录复用
    public static void login(Activity activity, LoginBean loginBean) {
        if (loginBean.isStatus()) {
            SharedPreferencesUtils.saveString(activity, "token", loginBean.getData().getUser().getLogin_token());
            SharedPreferencesUtils.saveString(activity, "uid", loginBean.getData().getUser().getUnid());
            SharedPreferencesUtils.saveString(activity, "face", loginBean.getData().getUser().getHeaderpic());
            JPushInterface.setAlias(activity, 1, loginBean.getData().getUser().getJpush_alias());
            activity.startActivity(new Intent(activity, MainActivity.class));
            if (loginBean.getData().getUser().getIs_first() == 1) {
                Constants.isFirst = true;
                activity.startActivity(new Intent(activity, SelectIndustryActivity.class));
            } else {
                activity.startActivity(new Intent(activity, MainActivity.class));
            }

            activity.finish();
        } else {
            ToastUtil.show(loginBean.getMsg());
        }
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone(Context activity, String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        activity.startActivity(intent);
    }

    public static boolean isEmpty(List<?> list) {
        return list == null || list.size() == 0;
    }

    //隐藏输入法
    public static void hideSoftInputWindow(Activity context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 切换软件盘 显示隐藏
     */
    public static void switchSoftInputMethod(Activity act) {
        // 方法一(如果输入法在窗口上已经显示，则隐藏，反之则显示)
        InputMethodManager iMM = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        iMM.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void imageUpload(BaseActivity activity, ArrayList<LocalMedia> result, NetCallBack callBack, int requestCode) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file = new File(result.get(0).getRealPath());
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("file", file.getName(), imageBody);
        builder.addFormDataPart("upload_file", "customer");
        builder.addFormDataPart("type", "app");
        List<MultipartBody.Part> parts = builder.build().parts();
        activity.loadingPopupShow();
        activity.networkRequest(activity.netApi.imageUpload(parts), callBack, requestCode);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static boolean isPhone(String str) {
        String regex = "^(1)\\d{10}$";//正则表达式
        return str.matches(regex);
    }

    public static boolean isCarnumberNO(String carnumber) {
        /*
         * 车牌号格式：汉字 + A-Z + 5位A-Z或0-9 （只包括了普通车牌号，教练车和部分部队车等车牌号不包括在内）
         */
        String carnumRegex = "[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5,6}";//在正则表达
        if (TextUtils.isEmpty(carnumber))
            return false;
        else
            return carnumber.matches(carnumRegex);
    }

    //禁止输入表情
    public static InputFilter[] inputFilters(Context context, int Length) {
        return new InputFilter[]{new InputFilter() {
            Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                Matcher emojiMatcher = emoji.matcher(source);

                if (emojiMatcher.find()) {
                    Toast.makeText(context, "不支持输入表情", Toast.LENGTH_SHORT).show();
                    //  MyToast.showText("不支持输入表情");
                    return "";
                }
                return null;
            }

        }, new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int i = start; i < end; i++) {
                    int type = Character.getType(source.charAt(i));
                    if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
                        Toast.makeText(context, "不支持输入表情", Toast.LENGTH_SHORT).show();
                        return "";
                    }
                }
                return null;
            }
        },
                /**这里限制输入的长度为200*/
                new InputFilter.LengthFilter(Length)};
    }

    /**
     * 将Bitmap图片保存到本地相册
     */
    public static void savePhotoToGallery(final Context context, final Bitmap bitmap) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 其次把文件插入到系统图库
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap,
                            "伞送物流", "测试 图集"); // 名字和描述没用，系统会自动更改
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.show("图片保存至相册");
                        }
                    });
                } catch (Exception e) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.show("图片保存失败");
                        }
                    });
                    LogUtils.e("图片保存异常：");
                }
            }
        }).start();
    }

    //验证银行卡号
    public static boolean checkBankCard(String cardId) {
        char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return cardId.charAt(cardId.length() - 1) == bit;
    }

    //从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
    public static char getBankCardCheckCode(String nonCheckCodeCardId) {
        if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    /**
     * 手机号中间四位隐藏
     *
     * @param phone 手机号
     */
    public static String phoneHide(String phone) {
        String phoneHide = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phoneHide;
    }

    public static String getCNCardType(int cardType) {
        switch (cardType) {
            case 1:
                return "储蓄卡";
            case 2:
                return "信用卡";
            case 3:
                return "准贷记卡";
            case 4:
                return "预支付卡";
            default:
                return "未知卡";
        }
    }

    public static String getCNCardTypeName(String cardType) {
        if (TextUtils.isEmpty(cardType)) return null;
        switch (cardType) {
            case "储蓄卡":
                return "1";
            case "信用卡":
                return "2";
            case "准贷记卡":
                return "3";
            case "预支付卡":
                return "4";
            default:
                return "未知卡";
        }
    }

    public static String getDeliverType(int type) {
        switch (type) {
            case 1:
                return "伞送普运";
            case 2:
                return "伞送快运";
            default:
                return "伞送议价";
        }
    }

    public static String get(int type) {
        switch (type) {
            case 1:
                return "微信";
            case 2:
                return "支付宝";
            default:
                return "银行卡";
        }
    }


    public static String getSexName(int type) {
        switch (type) {
            case 0:
                return "女";
            case 1:
                return "男";
            default:
                return "未设置";
        }
    }

    public static String getReceiptType(int type) {
        switch (type) {
            case 1:
                return "无需";
            case 2:
                return "回单";
            default:
                return "收条";
        }
    }

    /**
     * 使用java正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

    public static String setHint(OrderDetailsBean.DataDTO data) {
        switch (data.getOrder_info().getStatus()) {
            case 5:
                if (data.getOrder_info().getJiaohuo_type() == 1) {
                    return "已有公司接单，请尽快将货物送至专线";
                } else {
                    return "您的货物已入库等待物流公司发车";
                }
            case 7:
                return "您的货物已入库等待物流公司发车";
            case 9:
                return "【运输中】您的货物已发车正在运输中";
            case 11:
                if (data.getOrder_info().getPeisong_type() == 1) {
                    return String.format("您的货物已到达正在派送(取货码：%s)",data.getOrder_info().getSelf_pickup_code());
                } else {
                    return String.format("您的货物已到达，等待收货人取货(取货码：%s)",data.getOrder_info().getSelf_pickup_code());
                }
            case 15:
                return "待确认收货";
            case 20:
                return "订单已完成";
            case 80:
                return "订单已拒绝";
            case 90:
                return "订单已超时";
            case 99:
                if (data.getOrder_info().getCancel_status() == 1) {
                    return "订单已取消，请等待物流公司审核";
                } else {
                    return "已取消";
                }
            default:
                return "未知状态";
        }
    }

    public static void setAssistant(TextView tvAssistant, TextView tvLogisticsTrack, OrderDetailsBean.DataDTO data) {
        switch (data.getOrder_info().getStatus()) {
            case 90:
                tvLogisticsTrack.setVisibility(View.GONE);
                tvAssistant.setVisibility(View.VISIBLE);
                tvAssistant.setText("该订单由于长时间无人接单，已从货源大厅撤销！");
                break;
            case 99:
                tvLogisticsTrack.setVisibility(View.GONE);
                break;
            case 80:
                tvAssistant.setVisibility(View.VISIBLE);
                tvAssistant.setText(String.format("商家原因：”%s“原因，已拒绝了您的指派订单，您可以重新选择其他商家再次下单", data.getOrder_info().getRefuse_notice()));
                break;
            default:
                tvLogisticsTrack.setVisibility(View.VISIBLE);
                tvAssistant.setVisibility(View.GONE);
        }
    }

    public static String setStatus(String type) {
        switch (type) {
            case "1":
                return "询价中";
            case "2":
                return "已成交";
            case "3":
                return "已取消";
            default:
                return "未知";
        }
    }

    public static String getBefore(int timestamp) {
        if (android.text.format.DateUtils.getRelativeTimeSpanString(timestamp * 1000L).toString().startsWith("0")) {
            return "刚刚";
        } else {
            return DateUtils.getRelativeTimeSpanString(timestamp * 1000L).toString();
        }
    }

    public static void fileUpload(BaseActivity activity, File file, NetCallBack callBack, int requestCode) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("file", file.getName(), imageBody);
        builder.addFormDataPart("upload_file", "customer");
        builder.addFormDataPart("type", "app");
        List<MultipartBody.Part> parts = builder.build().parts();
        activity.networkRequest(activity.netApi.imageUpload(parts), callBack);

    }

    public static void fileUpload(BaseActivity activity, File file, NetCallBack callBack, int requestCode, boolean isCover) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("file", file.getName(), imageBody);
        builder.addFormDataPart("upload_file", "customer");
        builder.addFormDataPart("type", "app");
        List<MultipartBody.Part> parts = builder.build().parts();
        activity.networkRequest(activity.netApi.imageUpload(parts, "cover"), callBack);

    }

    /**
     * 小数点为0的修改为整数 其他不变
     * Created by xul on 2017/3/3.
     */
    public static String checkPoint(String num) {
        if (num.contains(".")) {
            StringBuilder myNum = new StringBuilder();
            try {
                String integerNum = num.substring(0, num.indexOf("."));
                String decimals = num.substring(num.indexOf("."), num.length());
                float decimalsNum = Float.valueOf(decimals);
                if (decimalsNum > 0) {
                    myNum = myNum.append(integerNum).append(decimals);
                } else {
                    myNum = myNum.append(integerNum);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            return String.valueOf(myNum);
        } else {
            return num;
        }
    }

    public static void getAbnormalStatus(TextView textView, String status) {
        if (TextUtils.isEmpty(status)) {
            textView.setText("驳回");
            textView.setTextColor(Color.parseColor("#D9001B"));
            return;
        }
        switch (status) {
            case "2":
            case "1":
                textView.setText("");
                break;
            case "3":
                textView.setText("驳回");
                textView.setTextColor(Color.parseColor("#D9001B"));
                break;
            case "5":
                textView.setText("同意");
                textView.setTextColor(Color.parseColor("#00AA3A"));
                break;
            case "7":
                textView.setText("已打款");
                textView.setTextColor(Color.parseColor("#00AA3A"));
                break;
            case "9":
                textView.setText("已撤销");
                textView.setTextColor(Color.parseColor("#000000"));
                break;
        }
    }

    public static String billType(String type, String num) {
        switch (type) {
            case "money01":
                if (Double.parseDouble(num) < 0) {
                    return "零钱支付";
                } else {
                    return "";
                }
            case "money02":
                if (Double.parseDouble(num) > 0) {
                    return "任务红包";
                } else {
                    return "红包抵扣";
                }
            case "weipay_mini":
            case "weipay_app":
                return "微信支付";
            case "alipay_app":
                return "支付宝支付";
            case "cash":
                return "现金支付";
            default:
                return "";
        }
    }
}
